package com.tricky.tron.trc20.job;

import com.tricky.tron.trc20.entity.Account;
import com.tricky.tron.trc20.service.AccountService;
import com.tricky.tron.trc20.service.TRXService;
import com.tricky.tron.trc20.service.Trc20Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

public class CoinCollectionJob {
    @Value("${tron.contract-address}")
    private String contractAddress;//hex格式

    private Logger logger = LoggerFactory.getLogger(CoinCollectionJob.class);
    @Autowired
    private AccountService accountService;
    @Autowired
    private TRXService trxService;
    @Autowired
    private Trc20Service trc20Service;


     /*为用户充值trx，充当gas*/
    @Scheduled(cron = "0 0 */1 * * ?")
    public void rechargeMinerFee(){
        List<Account> accountList = accountService.findAll();
        accountList.stream().forEach(account -> {
            //查询合约下账户的余额
            BigInteger trc20Balance = trc20Service.balanceOf(contractAddress,account.getAddress());
            BigInteger feeAmt = this.subtract(trc20Balance);
            if(feeAmt.compareTo(new BigInteger("0"))!=0){
                //转账矿工费
                trc20Service.feeAmtTransfer(account,feeAmt.toString());
            }
        });

    }
    public BigInteger subtract(BigInteger trc20Balance){
        if(trc20Balance.compareTo(new BigInteger("0"))==0){
            return new BigInteger("0");

        }
        if(trc20Balance.compareTo(new BigInteger("10000",16))<0){
            return new BigInteger("5");
        }else{
             return trc20Balance.multiply(new BigInteger("0.2")).add(trc20Balance);
        }
    }
}
